from django.apps import apps
from pytils.translit import slugify
from django.shortcuts import redirect
from django.shortcuts import render
from django.apps import apps
from django.db.models import Q

from content import forms
from content import models


class ContentManagement():

    """ Управление контентом """

    def get_list_of_parts_of_speech(self):

        """ Получаем список частей речи """

        list_of_parts_of_speech = 'glagoly mezhdometiya predlogi soyuzy artikli chislitelnye ' \
                                  'narechiya mestoimeniya prilagatelnye sushestvitelnye'.split()
        return list_of_parts_of_speech


    def get_list_of_initial_categories(self):

        """ Получаем список начальных категорий """

        list_of_initial_categories = []

        for category in models.Content.__subclasses__():
            entry = 'nachalnaya_' + category.__name__.lower()
            list_of_initial_categories.append(entry)

        return list_of_initial_categories


    def get_initial_group(self, content_type):

        """ Получаем начальную группу """

        list_of_initial_groups = {
            'phrase': 'nachalnaya_phrase',
            'rule': 'nachalnaya_rule',
            'article': 'nachalnaya_article',
            'image': 'nachalnaya_image',
        }
        group_slug = list_of_initial_groups[content_type]
        group = self.get_object('group', group_slug)
        return group


    def add_additional_information(self, object, note, photo):

        """ Добавляем дополнительную информацию """

        if note and photo:
            models.Additionaly.objects.create(note=note, photo=photo, content_object=object)
        if note:
            models.Additionaly.objects.create(note=note, content_object=object)
        if photo:
            models.Additionaly.objects.create(photo=photo, content_object=object)


    def check_object_being_deleted(self, object):

        """ Проверяем что собирается удалить пользователь """

        if object in self.get_list_of_initial_categories():
            return redirect('account:home_page')

    def add_group(self, content_type, object, cleaned_data):

        """ Добавляем группу объекту """

        if not object.group or cleaned_data['group'] == 'nachalnaya':
            print('тут выполняется')
            object.group = self.get_initial_group(content_type)
        else:
            print('нет тут выполняется')
            group = self.get_object('group', cleaned_data['group'])
            object.group = group


    def get_template(self, *data):

        """ Получаем шаблон """

        def get_template_to_update(data):

            """ Получаем шаблон для отображения обновления объекта """

            match data:
                case something, :
                    list_of_templates = {
                        'glagoly': 'content/update/update_verb.html',
                        'not_glagoly': 'content/update/update_word.html',
                        'phrase': 'content/update/update_phrase.html',
                        'additionally': 'content/update/update_additionally_information.html',
                        'group': 'content/update/group.html',
                        'rule': 'content/update/rule.html',
                        'article': 'content/update/article.html',
                        'image': 'content/update/image.html',
                    }
                    return list_of_templates[something]

                case _:
                    print(f'get_template_t_update - {data}')


        def get_template_to_add(data):

            """ Получаем шаблон для добавления """

            match data:
                case 'additionally', :
                    return 'content/add/additional_information.html'

                case 'group', content_type:
                    list_of_templates = {
                        'phrase': 'content/add/group.html',
                        'rule': 'content/add/group/rule.html',
                        'article': 'content/add/group/article.html',
                        'image': 'content/add/group/image.html',
                    }
                    return list_of_templates[content_type]

                case _:
                    print(data)


        def get_template_to_category(data):

            """ Показываем категорию какого-то типа содержимого """

            match data:
                case 'glagoly', :
                    return 'content/list/list_of_verbs.html'

                case 'phrase', :
                    return 'content/category/list_of_phrases.html'

                case 'rule', :
                    return 'content/category/list_of_rules.html'

                case 'article', :
                    return 'content/category/list_of_articles.html'

                case 'image', :
                    return 'content/category/list_of_image.html'

                case object_slug, :
                    return 'content/list/list_of_words.html'

                case _:
                    print(f'kjdfs923498235 - {data}')


        def get_template_to_detail(data):

            """ Получаем шаблон для детального отображения чего-то """

            match data:
                case 'glagoly', :
                    return 'content/detail/detail_verb.html'

                case 'not_glagoly', :
                    return 'content/detail/detail_word.html'

                case 'additionally', :
                    return 'content/detail/detail_additionally.html'

                case 'rule', :
                    return 'content/detail/rule.html'

                case 'article', :
                    return 'content/detail/article.html'

                case 'image', :
                    return 'content/detail/image.html'
                    

        # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        data = list(data)

        match data:
            case 'content_type', content_type:
                list_of_templates = {
                    'word': 'content/word.html',
                    'phrase': 'content/phrase.html',
                    'rule': 'content/rule.html',
                    'article': 'content/article.html',
                    'image': 'content/image.html',
                }
                return list_of_templates[content_type]

            case 'content_type', 'detail', content_type:
                list_of_templates = {
                    'phrase': 'content/detail/detail_phrase.html'
                }
                return list_of_templates[content_type]

            case 'part_of_speech', part_of_speech_slug:
                if part_of_speech_slug == 'glagoly':
                    return 'content/list/list_of_verbs.html'
                else:
                    return 'content/list/list_of_words.html'

            case 'add', 'part_of_speech', slug:
                list_of_templates = {
                    'glagoly': 'content/list/list_of_verbs.html'
                }
                return list_of_templates[slug]

            case 'category', *args:
                return get_template_to_category(args)

            case 'detail', *args:
                return get_template_to_detail(args)

            case 'add', *args:
                return get_template_to_add(args)

            case 'update', *args:
                return get_template_to_update(args)


            case _:
                print(f'data - {data}')


    def get_form(self, *data):

        """ Получаем форму """

        def get_form_for_category(data):

            """ Получаем форму для категории какого-то типа содержимого """

            match data:
                case 'glagoly', :
                    return forms.AddingVerbForm

                case object_slug, :
                    return forms.AddWordForm

                case _:
                    print(f'data002 - {data}')

        # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        match data:

            case 'add glagoly', :
                return forms.AddingVerbForm

            case 'add word', :
                return forms.AddWordForm

            case 'update word', :
                return forms.UpdateWordForm

            case 'add phrase', :
                return forms.AddPhraseForm

            case 'add additional information', :
                return forms.AddAdditionallyInformationForm

            case 'add group', :
                return forms.AddGroupForm

            case 'category', *args:
                return get_form_for_category(args)

            case 'add rule', :
                return forms.AddRuleForm

            case 'add article', :
                return forms.AddArticleForm

            case 'add image', :
                print('она')
                return forms.AddImageForm

            case _:
                print(f'get_form - {data}')


    def get_model(self, content_type):

        """ Получаем модель по какому-то параметру """

        print(f'content_type - {content_type}')
        model = apps.get_model(app_label='content', model_name=content_type)
        return model


    def get_part_of_speech(self, slug):

        """ Получаем часть речи """

        return models.PartOfSpeech.objects.get(slug=slug)


    def get_object(self, *data):

        """ Получаем какой-то объект """

        def get_object_for_category(data):

            """ Получаем объект категории """

            match data:
                case 'glagoly', :
                    return models.PartOfSpeech.objects.get(slug='glagoly')

                case 'phrase', object_slug:
                    return models.Group.objects.get(slug=object_slug)

                case 'group', object_slug:
                    return models.Group.objects.get(slug=object_slug)

                case 'rule', object_slug:
                    if object_slug == 'not_group':
                        return models.Group.objects.get(content='nachalnaya_rule')
                    else:
                        return models.Group.objects.get(slug=object_slug)

                case 'article', object_slug:
                    if object_slug == 'not_group':
                        return models.Group.objects.get(content='nachalnaya_article')
                    else:
                        return models.Group.objects.get(slug=object_slug)

                case 'image', object_slug:
                    if object_slug == 'not_group':
                        return models.Group.objects.get(content='nachalnaya_image')
                    else:
                        return models.Group.objects.get(slug=object_slug)

                case _:
                    print(f'838383838383838 - {data}')


        def get_object_for_delete(data):

            """ Получаем объект для удаления """

            match data:
                case 'word', content_type, object_slug:
                    if content_type == 'glagoly':
                        object = models.Verb.objects.get(slug=object_slug)
                        return object
                    else:
                        object = models.Word.objects.get(slug=object_slug)
                        return object

                case 'phrase', content_type, object_slug:
                    object = models.Phrase.objects.get(slug=object_slug)
                    return object


        # ВЫШЕ ОПРЕДЛЕНИЕ ФУНКЦИЙ

        data = list(data)

        match data:

            case 'glagoly', slug:
                return models.Verb.objects.get(slug=slug)

            case 'not_glagoly', object_slug:
                return models.Word.objects.get(slug=object_slug)

            case 'word', object_slug:
                return self.get_word(object_slug)

            case 'phrase', object:
                return models.Phrase.objects.get(slug=object)

            case 'additionally', pk:
                return models.Additionaly.objects.get(pk=pk)

            case 'category', *args:
                return get_object_for_category(args)

            case 'group', object_slug:
                return models.Group.objects.get(slug=object_slug)

            case 'rule', object_slug:
                return models.Rule.objects.get(slug=object_slug)

            case 'article', object_slug:
                return models.Article.objects.get(slug=object_slug)

            case 'image', object_slug:
                return models.Image.objects.get(slug=object_slug)

            case 'delete', *args:
                return  get_object_for_delete(args)


    def get_groups(self, content_type):

        """ Получаем все группы какого-то содержимого """

        initial_group = self.get_initial_group(content_type)
        groups = models.Group.objects.filter(Q(content=content_type) | Q(slug=initial_group))
        return groups


    def get_object_type(self, object_slug):

        """ Получаем тип объекта """

        object = self.get_word(object_slug)
        object_name = type(object).__name__.lower()
        return object_name


    def get_word(self, object_slug):

        """ Получаем слово """

        if models.Verb.objects.filter(slug=object_slug).exists():
            return self.get_object('glagoly', object_slug)
        else:
            return self.get_object('not_glagoly', object_slug)


    def delete_object(self, content_type, object_slug):

        """ Удаляем какой-то объект """

        object = self.get_object(content_type, object_slug)
        object.delete()


    def get_context(self, *data):

        """ Получаем контекст для шаблона """

        def get_context_for_content_type(content_type):

            """ Получаем контекст для какого-то типа контента (видео, слова, статьи) """

            def get_context_for_rule():

                """ Получаем контекст для правил """

                content_type = 'rule'
                form = self.get_form('add rule')
                rules = models.Rule.objects.all()
                groups = self.get_groups(content_type)
                context = {'selected': 'rule',
                           'rules': rules,
                           'content_type': 'rule',
                           'groups': groups,
                           'form': form}
                return context


            def get_context_for_article():

                """ Получаем контекст для статей """

                content_type = 'article'
                form = self.get_form('add article')
                articles = models.Article.objects.all()
                groups = self.get_groups(content_type)
                context = {'selected': 'article',
                           'articles': articles,
                           'content_type': 'article',
                           'groups': groups,
                           'form': form}
                return context


            def get_context_for_image():

                """ Получаем контекст для изображений """

                content_type = 'image'
                form = self.get_form('add image')
                images = models.Image.objects.all()
                groups = self.get_groups(content_type)
                context = {'selected': 'image',
                           'images': images,
                           'content_type': content_type,
                           'groups': groups,
                           'form': form}
                return context

            # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

            if content_type == 'word':
                part_of_speech = models.PartOfSpeech.objects.all()
                context = {'parts_of_speech': part_of_speech,
                           'selected': 'word',
                           'content_type': content_type}
            elif content_type == 'phrase':
                phrase = self.get_model(content_type)
                form = self.get_form('add phrase')
                groups = self.get_groups(content_type)
                context = {'selected': 'phrase',
                           'content_type': content_type,
                           'phrase_model': phrase,
                           'form': form,
                           'groups': groups}

            elif content_type == 'rule':
                return get_context_for_rule()

            elif content_type == 'article':
                return get_context_for_article()

            elif content_type == 'image':
                return get_context_for_image()

            return context


        def get_context_for_content_type_detail(data):

            """ Получаем контекст для отдельного объекта какого-то типа содержимго """

            match data:
                case 'phrase', object:
                    model = self.get_model('phrase')
                    object = model.objects.get(slug=object)
                    context = {'selected': 'phrase', 'phrase': object}
                    return context

                case _:
                    print(f'get_context_for_content - {data}')


        def get_context_for_update(data):

            """ Получаем контекст для страницы с обновлением какого-то объекта """

            def get_context_for_update_additionally(pk):

                """ Получаем контекст для обновления дополнительной информации объекта """

                object = self.get_object('additionally', pk)
                form = self.get_form('add additional information')
                form = form(instance=object)
                context = {'form': form, 'object': object, 'selected': 'phrase'}
                return context


            def get_context_for_update_rule(object_slug):

                """ Получаем контекст для обновления правила """

                object = self.get_object('rule', object_slug)
                form = self.get_form('add rule')
                form = form(instance=object)
                context = {'selected': 'rule',
                           'form': form,
                           'object': object}
                return context


            def get_context_for_update_article(object_slug):

                """ Получаем контекст для обновления статьи """

                content_type = 'article'
                object = self.get_object(content_type, object_slug)
                form = self.get_form('add article')
                form = form(instance=object)
                context = {'selected': 'article',
                           'form': form,
                           'object': object}
                return context


            def get_context_for_update_image(object_slug):

                """ Получаем контекст для обновления изображения """

                content_type = 'image'
                object = self.get_object(content_type, object_slug)
                form = self.get_form('add image')
                form = form(instance=object)
                context = {'selected': 'image',
                           'form': form,
                           'object': object}
                return context


            # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

            match data:
                case 'glagoly', object_slug:
                    object = self.get_object('glagoly', object_slug)
                    form = self.get_form('add glagoly')
                    form = form(instance=object)
                    context = {'form': form,
                               'selected': 'word',
                               'part_of_speech': 'glagoly',
                               'word': object_slug}
                    return context

                case not_glagoly, object_slug if not_glagoly in self.get_list_of_parts_of_speech()[1:]:
                    object = self.get_object('not_glagoly', object_slug)
                    form = self.get_form('update word')
                    form = form(instance=object)
                    context = {'selected': 'word',
                               'form': form,
                               'part_of_speech': not_glagoly,
                               'word': object}
                    return context

                case 'phrase', object:
                    model = self.get_model('phrase')
                    object = model.objects.get(slug=object)
                    form = self.get_form('add phrase')
                    form = form(instance=object)
                    context = {'selected': 'phrase', 'object': object, 'form': form}
                    return context

                case 'additionally', pk:
                    return get_context_for_update_additionally(pk)

                case 'group', object_slug:
                    object = self.get_object('category', 'group', object_slug)
                    form = self.get_form('add group')
                    form = form(instance=object)
                    context = {'selected': object.content, 'form': form, 'object': object}
                    return context

                case 'rule', object_slug:
                    return get_context_for_update_rule(object_slug)

                case 'article', object_slug:
                    return get_context_for_update_article(object_slug)

                case 'image', object_slug:
                    return get_context_for_update_image(object_slug)

                case _:
                    print(f'0193 - {data}')


        def get_context_for_add(data):

            """ Получаем контекст для добавления """

            match data:
                case 'additionally', content_type, object:
                    form = self.get_form('add additional information')
                    object = self.get_object(content_type, object)
                    context = {'form': form, 'object': object, 'selected': content_type}
                    return context

                case 'group', content_type:
                    form = self.get_form('add group')
                    context = {'selected': content_type, 'form': form, 'content_type': content_type}
                    return context

                case _:
                    print(f'01010110 - {data}')


        def get_context_for_detail(data):

            """ Получаем контекст для детального отображения какого-то объекта """

            def get_context_for_detail_verb(data):

                """ Получаем контекс для отображения глагола """

                verb_slug = data[0]
                object = self.get_object('glagoly', verb_slug)
                context = {'selected': 'word', 'verb': object}
                return context


            def get_context_for_detail_not_verb(not_glagoly_slug, object_slug):

                """ Контекст для отображения слова, отличного от глагола """

                object = self.get_object('not_glagoly', object_slug)
                context = {'selected': 'word', 'word': object}
                return context


            def get_context_for_detail_additionally(pk):

                """ Получаем контекст для детального отображения дополнительной информации """

                object = self.get_object('additionally', pk)
                context = {'selected': 'phrase', 'object': object}
                return context


            def get_context_for_detail_rule(object_slug):

                """ Получаем контекст для детального отображения правила """

                content_type = 'rule'
                object = self.get_object(content_type, object_slug)
                context = {'selected': content_type,
                           'object': object,
                           'content_type': content_type}
                return context


            def get_context_for_detail_article(object_slug):

                """ Получаем контекст для детального отображения статьи """

                content_type = 'article'
                object = self.get_object(content_type, object_slug)
                context = {'selected': content_type,
                           'object': object,
                           'content_type': content_type}
                return context


            def get_context_for_detail_image(object_slug):

                """ Получаем контекст для детального отображения статьи """

                content_type = 'image'
                object = self.get_object(content_type, object_slug)
                context = {'selected': content_type,
                           'object': object,
                           'content_type': content_type}
                return context


            # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

            match data:
                case 'glagoly', *args:
                    return get_context_for_detail_verb(args)

                case 'not_glagoly', not_glagoly_slug, object_slug:
                    return get_context_for_detail_not_verb(not_glagoly_slug, object_slug)

                case 'additionally', pk:
                    return get_context_for_detail_additionally(pk)

                case 'rule', object_slug:
                    return get_context_for_detail_rule(object_slug)

                case 'article', object_slug:
                    return get_context_for_detail_article(object_slug)

                case 'image', object_slug:
                    return get_context_for_detail_image(object_slug)


        def get_context_for_category(data):

            """ Получаем контекс для категории какого-то типа содержимого """

            def get_context_for_category_word(data):

                """ Получаем контекст для категорий слов """

                match data:
                    case 'glagoly':
                        object_slug = 'glagoly'
                        form = self.get_form('category', object_slug)
                        object = self.get_object('category', object_slug)
                        context = {'selected': 'word',
                                   'form': form,
                                   'part_of_speech': object,
                                   'content_type': 'word'}
                        return context

                    case object_slug, :
                        form = self.get_form('category', object_slug)
                        part_of_speech = self.get_part_of_speech(object_slug)
                        context = {'selected': 'word', 'part_of_speech': part_of_speech, 'form': form,}
                        return context

                    case _:
                        print(f'dataglgogl - {data}')


            def get_context_for_category_phrase(object_slug):

                """ Получаем контекст для какой-то категории фраз """

                category = self.get_object('category', 'phrase', object_slug)
                phrases = models.Phrase.objects.filter(group=category)
                context = {'selected': 'phrase',
                           'list_of_initial_categories': self.get_list_of_initial_categories(),
                           'category': category,
                           'list_of_phrases': phrases,
                           'object_slug': object_slug}
                return context


            def get_context_for_category_rule(object_slug):

                """ Получаем контекст для отображения какой-то категории правил """

                category = self.get_object('category', 'rule', object_slug)
                rules = models.Rule.objects.filter(group=category)
                context = {'selected': 'rule',
                           'list_of_initial_categories': self.get_list_of_initial_categories(),
                           'category': category,
                           'rules': rules}
                return context


            def get_context_for_category_article(object_slug):

                """ Получаем контекс для отображения какой-то категории статей """

                content_type = 'article'
                category = self.get_object('category', content_type, object_slug)
                articles = models.Article.objects.filter(group=category)
                context = {'selected': 'article',
                           'list_of_initial_categories': self.get_list_of_initial_categories(),
                           'category': category,
                           'articles': articles}
                return context


            def get_context_for_category_image(object_slug):

                """ Получаем контекс для отображения какой-то категории изображения """

                content_type = 'image'
                category = self.get_object('category', content_type, object_slug)
                images = models.Image.objects.filter(group=category)
                context = {'selected': 'image',
                           'list_of_initial_categories': self.get_list_of_initial_categories(),
                           'category': category,
                           'images': images}
                return context

            # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

            match data:
                case 'word', args:
                    return get_context_for_category_word(args)

                case 'phrase', object_slug:
                    return get_context_for_category_phrase(object_slug)

                case 'rule', object_slug:
                    return get_context_for_category_rule(object_slug)

                case 'article', object_slug:
                    return get_context_for_category_article(object_slug)

                case 'image', object_slug:
                    return get_context_for_category_image(object_slug)
                    

        # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        match data:
            case 'content_type', content_type:
                return get_context_for_content_type(content_type)

            case 'content_type', 'detail', *args:
                return get_context_for_content_type_detail(args)

            case 'detail', *args:
                return get_context_for_detail(args)

            case 'add', *args:
                return get_context_for_add(args)

            case 'update', *args:
                return get_context_for_update(args)

            case 'category', *args:
                return get_context_for_category(args)

            case _:
                print(f'data02 - {data}')


    def show_something(self, data):

        """ Показываем что-то """

        def show_content_type(content_type):

            """ Показываем какой-то тип содержимого (видео, фразы, правила) """

            template = self.get_template('content_type', content_type)
            context = self.get_context('content_type', content_type)
            return (template, context)


        def show_phrase(object):

            """ Показываем фразу """

            template = self.get_template('content_type', 'detail', 'phrase')
            context = self.get_context('content_type', 'detail', 'phrase', object)
            return template, context


        def show_adding_something(data):

            """ Показываем страницу для добавления чего-то """

            def show_adding_additional_object(content_type, object):

                """ Показываем добавление дополнительного объекта """

                template = self.get_template('add', 'additionally')
                context = self.get_context('add', 'additionally', content_type, object)
                return template, context


            def show_adding_group(content_type):

                """ Показываем добавление группы """

                template = self.get_template('add', 'group', content_type)
                context = self.get_context('add', 'group', content_type)
                return (template, context)

            # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

            match data:
                case 'additionally', content_type, object:
                    return show_adding_additional_object(content_type, object)

                case 'group', content_type:
                    return show_adding_group(content_type)

                case _:
                    print(f'additionally - {data}')


        def show_update_something(data):

            """ Показываем страницу обнавления чего-то """

            def show_update_word(not_glagoly_slug, object_slug):

                """ Показываем обновление для слова отличного от глагола """

                template = self.get_template('update', 'not_glagoly')
                context = self.get_context('update', not_glagoly, object)
                return template, context


            def show_update_phrase(data):

                """ Показываем обновление фразы """

                object = data
                template = self.get_template('update', 'phrase')
                context = self.get_context('update', 'phrase', object)
                return template, context


            def show_update_additionally(data):

                """ Показываем страницу обновлния для дополнительной информации объекта """

                type_of_main_object, main_object, content_type, request, pk = data
                template = self.get_template('update', 'additionally')
                context = self.get_context('update', 'additionally', pk)
                return template, context

            def show_update_group(object_slug):

                """ Показываем обновление для группы """

                template = self.get_template('update', 'group')
                context = self.get_context('update', 'group', object_slug)
                return (template, context)


            def show_update_rule(object_slug):

                """ Показываем обновление для правила """

                template = self.get_template('update', 'rule')
                context = self.get_context('update', 'rule', object_slug)
                return (template, context)


            def show_update_article(object_slug):

                """ Показываем обновление для статьи """

                content_type = 'article'
                template = self.get_template('update', content_type)
                context = self.get_context('update', content_type, object_slug)
                return (template, context)


            def show_update_image(object_slug):

                """ Показываем обновление для изображения """

                content_type = 'image'
                template = self.get_template('update', content_type)
                context = self.get_context('update', content_type, object_slug)
                return (template, context)

            # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

            match data:
                case 'glagoly', object:
                    template = self.get_template('update', 'glagoly')
                    context = self.get_context('update', 'glagoly', object)
                    return template, context

                case not_glagoly, object if data[0] in self.get_list_of_parts_of_speech()[1:]:
                    return show_update_word(not_glagoly, object)

                case 'phrase', object:
                    return show_update_phrase(object)

                case 'additionally', *args:
                    return show_update_additionally(args)

                case 'group', object_slug:
                    return show_update_group(object_slug)

                case 'rule', object_slug:
                    return show_update_rule(object_slug)

                case 'article', object_slug:
                    return show_update_article(object_slug)

                case 'image', object_slug:
                    return show_update_image(object_slug)

                case _:
                    print(f'show_update_something - {data}')


        def show_additionally(data):

            """ Показываем дополнительную информацию какого-то объекта """

            pk = data[0]
            print(f'pk - {pk}')
            template = self.get_template('detail', 'additionally')
            context = self.get_context('detail', 'additionally', pk)
            return template, context


        def show_glagoly(glagoly_slug):

            """ Показываем глагол """

            template = self.get_template('detail', 'glagoly')
            context = self.get_context('detail', 'glagoly', glagoly_slug)
            return (template, context)


        def show_not_glagoly(not_glagoly_slug, object_slug):

            """ Показываем часть речи отличную от глагола """

            template = self.get_template('detail', 'not_glagoly')
            context = self.get_context('detail', 'not_glagoly', not_glagoly_slug, object_slug)
            return template, context


        def show_category(data):

            """ Показываем категорию какого-то типа объекта """

            def show_category_for_word(data):

                """ Показываем категорию для слов (часть речи) """

                match data:
                    case 'glagoly', :
                        object_slug = 'glagoly'
                        template = self.get_template('category', object_slug)
                        context = self.get_context('category', 'word', object_slug)
                        return template, context

                    case object_slug if object_slug != 'glagoly':
                        template = self.get_template('category', object_slug)
                        context = self.get_context('category', 'word', object_slug)
                        return template, context

                    case _:
                        print(f'gl - {data}')


            def show_category_for_phrase(object_slug):

                """ Показываем категорию для фраз """

                template = self.get_template('category', 'phrase')
                context = self.get_context('category', 'phrase', object_slug)
                return (template, context)


            def show_category_for_rule(object_slug):

                """ Показываем категорию правил """

                template = self.get_template('category', 'rule')
                context = self.get_context('category', 'rule', object_slug)
                return (template, context)


            def show_category_for_article(object_slug):

                """ Показываем категорию статей """

                content_type = 'article'
                template = self.get_template('category', content_type)
                context = self.get_context('category', content_type, object_slug)
                return (template, context)


            def show_category_for_image(object_slug):

                """ Показываем категорию статей """

                content_type = 'image'
                template = self.get_template('category', content_type)
                context = self.get_context('category', content_type, object_slug)
                return (template, context)


            # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

            match data:
                case 'word', *args:
                    return show_category_for_word(args)

                case 'phrase', object_slug:
                    return show_category_for_phrase(object_slug)

                case 'rule', object_slug:
                    return show_category_for_rule(object_slug)

                case 'article', object_slug:
                    return show_category_for_article(object_slug)

                case 'image', object_slug:
                    return show_category_for_image(object_slug)

                case _:
                    print(f'444444444444 - {data}')


        def show_word(object_slug):

            """ Показываем слово """

            object_type = self.get_object_type(object_slug)

            if object_type == 'verb':
                data = ['glagoly', object_slug]
                return self.show_something(data)
            if object_type == 'word':
                object = self.get_object('not_glagoly', object_slug)
                data = [object.part_of_speech.slug, object_slug]
                return self.show_something(data)


        def show_rule(object_slug):

            """ Показываем правило """

            content_type = 'rule'
            template = self.get_template('detail', content_type)
            context = self.get_context('detail', content_type, object_slug)
            return (template, context)


        def show_article(object_slug):

            """ Показываем статью """

            content_type = 'article'
            template = self.get_template('detail', content_type)
            context = self.get_context('detail', content_type, object_slug)
            return (template, context)


        def show_image(object_slug):

            """ Показываем изображение """

            content_type = 'image'
            template = self.get_template('detail', content_type)
            context = self.get_context('detail', content_type, object_slug)
            return (template, context)


        # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        match data:
            case 'content_type', content_type:
                return show_content_type(content_type)

            case 'additionally', *args:
                return show_additionally(args)

            case 'glagoly', object:
                return show_glagoly(object)

            case not_glagoly, object_slug if data[0] in self.get_list_of_parts_of_speech()[1:]:
                return show_not_glagoly(not_glagoly, object_slug)

            case 'word', object_slug:
                return show_word(object_slug)

            case 'phrase', object:
                return show_phrase(object)

            case 'rule', object_slug:
                return show_rule(object_slug)

            case 'article', object_slug:
                return show_article(object_slug)

            case 'image', object_slug:
                return show_image(object_slug)

            case 'category', *args:
                return show_category(args)

            case 'add', *args:
                return show_adding_something(args)

            case 'update', *args:
                return show_update_something(args)

            case _:
                print(f'data0 - {data}')


    def update_something(self, data):

        """ Обновляем что-то """

        def update_glagoly(data):

            """ Обновляем глагол """

            request, object_slug = data
            object = self.get_object('glagoly', object_slug)
            form = self.get_form('add glagoly')
            bound_form = form(request.POST, request.FILES, instance=object)

            if bound_form.is_valid():
                cleaned_data = bound_form.cleaned_data
                new_object = bound_form.save(commit=False)
                new_object.slug = slugify(cleaned_data['word'])
                new_object.save()
                return redirect('content:showing_object_detail', content_type='glagoly', object=new_object.slug)

        def update_not_glagoly(not_glagoly, request, object_slug):

            """ Обновляем слово, отличное от глагола """

            object = self.get_object('not_glagoly', object_slug)
            form = self.get_form('add word')
            bound_form = form(request.POST, request.FILES, instance=object)

            if bound_form.is_valid():
                cleaned_data = bound_form.cleaned_data
                print(f'cleda - {cleaned_data}')
                new_object = bound_form.save(commit=False)
                new_object.slug = slugify(cleaned_data['word'])
                new_object.save()
                return redirect('content:showing_object_detail', content_type=not_glagoly, object=new_object.slug)


        def update_phrase(request, object):

            """ Обновляем фразу """

            obj = self.get_object('phrase', object)
            form = self.get_form('add phrase')
            bound_form = form(request.POST, request.FILES, instance=obj)

            if bound_form.is_valid():
                cleaned_data = bound_form.cleaned_data
                print(f'cleaned_datablabla - {cleaned_data}')
                new_phrase = bound_form.save(commit=False)

                self.add_group('phrase', new_phrase, cleaned_data)
                slug = slugify(cleaned_data['phrase'])
                new_phrase.slug = slug
                new_phrase.save()
                self.add_additional_information(new_phrase, cleaned_data['note'], cleaned_data['photo'])

                return redirect('content:showing_object_detail', content_type='phrase', object=slug)


        def update_additionally(data):

            """ Обновляем дополнительную информацию об объекте """

            type_of_main_object, main_object_slug, content_type, request, object_pk = data
            type_of_main_object = 'glagoly' if type_of_main_object == 'verb' else type_of_main_object  # Проблема с именами
            main_object = self.get_object(type_of_main_object, main_object_slug)
            addition = self.get_object('additionally', object_pk)
            form = self.get_form('add additional information')
            bound_form = form(request.POST, request.FILES, instance=addition)

            if bound_form.is_valid():
                new_object = bound_form.save(commit=False)
                new_object.content_object = main_object
                new_object.save()
                return redirect('content:showing_object_detail', content_type=type_of_main_object, object=main_object_slug)
            else:
                pass

        def update_group(request, object_slug):

            """ Обновляем группу какого-то контента """

            object = self.get_object('category', 'group', object_slug)
            form = self.get_form('add group')
            form = form(request.POST, instance=object)

            if form.is_valid():
                new_object = form.save(commit=False)
                new_object.slug = slugify(new_object.slug)
                new_object.save()
                result = redirect(request.session['previous_page'])
                del request.session['previous_page']
                return result


        def update_rule(request, object_slug):

            """ Обновляем какое-то правило """

            object = self.get_object('rule', object_slug)
            form = self.get_form('add rule')
            form = form(request.POST, instance=object)

            if form.is_valid():
                new_object = form.save(commit=False)
                new_object.slug = slugify(new_object.slug)
                if not new_object.group:
                    new_object.group = self.get_initial_group('rule')
                new_object.save()
                return redirect('content:showing_object_detail', content_type='rule', object=object_slug)


        def update_article(request, object_slug):

            """ Обновляем какую-то статью """

            content_type = 'article'
            object = self.get_object(content_type, object_slug)
            form = self.get_form('add article')
            form = form(request.POST, instance=object)

            if form.is_valid():
                new_object = form.save(commit=False)
                new_object.slug = slugify(new_object.slug)
                if not new_object.group:
                    new_object.group = self.get_initial_group(content_type)
                new_object.save()
                return redirect('content:showing_object_detail', content_type=content_type, object=object_slug)


        def update_image(request, object_slug):

            """ Обновляем какое-то изображение """

            content_type = 'image'
            object = self.get_object(content_type, object_slug)
            form = self.get_form('add image')
            bound_form = form(request.POST, request.FILES, instance=object)

            if bound_form.is_valid():
                new_object = bound_form.save(commit=False)
                new_object.slug = slugify(new_object.slug)
                if not new_object.group:
                    new_object.group = self.get_initial_group(content_type)
                new_object.save()
                return redirect('content:showing_object_detail', content_type=content_type, object=object_slug)


        # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        match data:
            case 'glagoly', *args:
                return update_glagoly(args)

            case not_glagoly, request, object if data[0] in self.get_list_of_parts_of_speech()[1:]:
                return update_not_glagoly(not_glagoly, request, object)

            case 'phrase', request, object:
                return update_phrase(request, object)

            case 'additionally', *args:
                return update_additionally(args)

            case 'group', request, object_slug:
                return update_group(request, object_slug)

            case 'rule', request, object_slug:
                return update_rule(request, object_slug)

            case 'article', request, object_slug:
                return update_article(request, object_slug)

            case 'image', request, object_slug:
                return update_image(request, object_slug)

            case _:
                print(f'data01 - {data}')


    def add_something(self, data):

        """ Добавляем что-то """

        def add_verb(request):

            """ Добавляем глагол """

            form = self.get_form('add glagoly')
            bound_form = form(request.POST, request.FILES)

            if bound_form.is_valid():
                cleaned_data = bound_form.cleaned_data
                new_object = bound_form.save(commit=False)
                new_object.slug = slugify(cleaned_data['word'])
                new_object.part_of_speech = self.get_part_of_speech('glagoly')
                new_object.save()
                return redirect('content:showing_object_category', 'word', 'glagoly')


        def add_not_glagoly(request, not_glagoly):

            """ Добавляем слово, отличное от глагола """

            part_of_speech = self.get_part_of_speech(not_glagoly)
            form = self.get_form('add word')
            bound_form = form(request.POST, request.FILES)

            if bound_form.is_valid():
                cleaned_data = bound_form.cleaned_data
                new_object = bound_form.save(commit=False)
                new_object.slug = cleaned_data['word']
                new_object.part_of_speech = part_of_speech
                new_object.save()
                self.add_additional_information(new_object, cleaned_data['note'], cleaned_data['photo'])
                return redirect('content:showing_object_category', content_type='word', object=not_glagoly)
            else:
                print('не валидно ни че го')


        def add_phrase(request, content_type):

            """ Добавляем фразу """

            form  = self.get_form('add phrase')
            bound_form = form(request.POST, request.FILES)

            if bound_form.is_valid():
                cleaned_data = bound_form.cleaned_data
                print(f'cleaned_data - {cleaned_data}')
                object_slug = slugify(cleaned_data['phrase'])
                new_object = bound_form.save(commit=False)
                if not new_object.group:
                    new_object.group = self.get_initial_group('phrase')
                new_object.slug = object_slug
                new_object.save()

                models.Additionaly.objects.create(note=cleaned_data['note'],
                                                  photo=cleaned_data['photo'],
                                                  content_object=new_object)

                return redirect('content:showing_object_detail', content_type='phrase', object=object_slug)


        def add_additional_information(data):

            """ Добавляем дополнительную информацию к объекту """

            request, content_type, object = data
            form = self.get_form('add additional information')
            bound_form = form(request.POST, request.FILES)

            if bound_form.is_valid():
                new_object = bound_form.save(commit=False)
                related_object = self.get_object(content_type, object)
                new_object.content_object = related_object
                new_object.save()
                return redirect('content:showing_object_detail', content_type=content_type, object=object)
            else:
                print('bbbbbbbbbbbbbbbbbbbbbbb')


        def add_group(data):

            """ Добавляем группу для какого-то типа содержимого """

            match data:
                case request, 'phrase':
                    form = self.get_form('add group')
                    bound_form = form(request.POST)

                    if bound_form.is_valid():
                        new_object = bound_form.save(commit=False)
                        new_object.slug = slugify(new_object.name)
                        new_object.content = 'phrase'
                        new_object.save()
                        return redirect('content:showing_content', content_type='phrase')

                case request, 'rule':
                    form = self.get_form('add group')
                    bound_form = form(request.POST)

                    if bound_form.is_valid():
                        new_object = bound_form.save(commit=False)
                        new_object.slug = slugify(new_object.name)
                        new_object.content = 'rule'
                        new_object.save()
                        return redirect('content:showing_content', content_type='rule')

                case request, 'article':
                    form = self.get_form('add group')
                    bound_form = form(request.POST)

                    if bound_form.is_valid():
                        content_type = 'article'
                        new_object = bound_form.save(commit=False)
                        new_object.slug = slugify(new_object.name)
                        new_object.content = content_type
                        new_object.save()
                        return redirect('content:showing_content', content_type=content_type)

                case request, 'image':
                    form = self.get_form('add group')
                    bound_form = form(request.POST)

                    if bound_form.is_valid():
                        content_type = 'image'
                        new_object = bound_form.save(commit=False)
                        new_object.slug = slugify(new_object.name)
                        new_object.content = content_type
                        new_object.save()
                        return redirect('content:showing_content', content_type=content_type)


        def add_rule(request):

            """ Добавляем правило """

            form = self.get_form('add rule')
            bound_form = form(request.POST)

            if bound_form.is_valid():
                cleaned_data = bound_form.cleaned_data
                print(f'cleaned_data - {cleaned_data}')
                object_slug = slugify(cleaned_data['title'])
                new_object = bound_form.save(commit=False)
                if not new_object.group:
                    new_object.group = self.get_initial_group('rule')
                new_object.slug = object_slug
                new_object.save()
                return redirect('content:showing_object_detail', content_type='rule', object=object_slug)


        def add_article(request):

            """ Добавляем статью """

            content_type = 'article'
            form = self.get_form('add article')
            bound_form = form(request.POST)

            if bound_form.is_valid():
                cleaned_data = bound_form.cleaned_data
                print(f'cleaned_data - {cleaned_data}')
                object_slug = slugify(cleaned_data['title'])
                new_object = bound_form.save(commit=False)
                if not new_object.group:
                    new_object.group = self.get_initial_group(content_type)
                new_object.slug = object_slug
                new_object.save()
                return redirect('content:showing_object_detail', content_type=content_type, object=object_slug)


        def add_image(request):

            """ Добавляем изображение """

            content_type = 'image'
            form = self.get_form('add image')
            print(f'form - {form}')
            print(f'form - {form._meta.fields}')
            print(f'form - {request.FILES}')
            bound_form = form(request.POST, request.FILES)
            print('uuuuuuuuutuuuuuuuut')

            if bound_form.is_valid():
                cleaned_data = bound_form.cleaned_data
                object_slug = slugify(cleaned_data['title'])
                new_object = bound_form.save(commit=False)
                print('uuuuuuuuutuuuuuuuut2')
                if not new_object.group:
                    new_object.group = self.get_initial_group(content_type)
                new_object.slug = object_slug
                new_object.save()
                print('uuuuuuuuutuuuuuuuut1')
                return redirect('content:showing_object_detail', content_type=content_type, object=object_slug)
            else:
                print(f'errors - {bound_form.errors}')
                cleaned_data = bound_form.cleaned_data
                print(f'cleaned_data - {cleaned_data}')
                print('uuuuuuuuutuuuuuuuut3')


        # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        match data:
            case request, 'word', 'glagoly':
                return add_verb(request)

            case request, 'word', not_glagoly if data[-1] in self.get_list_of_parts_of_speech()[1:]:
                return add_not_glagoly(request, not_glagoly)

            case request, 'phrase':
                return add_phrase(request, 'phrase')

            case request, 'rule':
                return add_rule(request)

            case request, 'article':
                return add_article(request)

            case request, 'image':
                return add_image(request)

            case 'additionally', *args:
                return add_additional_information(args)

            case 'group', *args:
                return add_group(args)

            case _:
                print(f'abc - {data}')


    def delete_something(self, data):

        """ Удаляем что-то """

        def delete_word(data):

            """ Удаляем слово """

            match data:
                case request, 'glagoly', object_slug:
                    object = self.get_object('delete', 'word', 'glagoly', object_slug)
                    object.delete()
                    return redirect('content:showing_object_category', content_type='word', object='glagoly')

                case request, content_type, object_slug if data[1] in self.get_list_of_parts_of_speech()[1:]:
                    object = self.get_object('delete', 'word', content_type, object_slug)
                    object.delete()
                    return redirect('content:showing_object_category', content_type='word', object=content_type)


        def delete_phrase(data):

            """ Удаляем фразу """

            match data:
                case request, category, object_slug:
                    print(f'category - {category}')
                    object = self.get_object('delete', 'phrase', category, object_slug)
                    object.delete()
                    return redirect('content:showing_object_category', content_type='phrase', object=category)


        def delete_additionally(pk):

            """ Удаляем дополнительную информацию """

            additionally = self.get_object('additionally', pk)
            related_object_slug = additionally.content_object.slug
            content_type = type(additionally.content_object).__name__.lower()
            content_type = 'glagoly' if content_type == 'verb' else content_type  # Проблема с именами
            additionally.delete()
            return redirect('content:showing_object_detail', content_type=content_type, object=related_object_slug)


        def delete_group(data):

            """ Удаляем группы """

            request, content_type, object_slug = data
            result = self.check_object_being_deleted(object_slug)
            if result: return result  # Если запрос на удаление начальной гурппы - перенаправляем

            object = self.get_object('group', object_slug)
            object.delete()
            return redirect('content:showing_content', content_type=content_type)


        def delete_rule(data):

            """ Удаляем правило """

            request, content_type, object_slug = data
            object = self.get_object('rule', object_slug)
            object.delete()
            return redirect('content:showing_object_category', content_type='rule', object=content_type)


        def delete_article(data):

            """ Удаляем статью """

            main_content_type = 'article'
            request, content_type, object_slug = data
            object = self.get_object(main_content_type, object_slug)
            object.delete()
            return redirect('content:showing_object_category', content_type=main_content_type, object=content_type)


        def delete_image(data):

            """ Удаляем изображение """

            main_content_type = 'image'
            request, content_type, object_slug = data
            object = self.get_object(main_content_type, object_slug)
            object.delete()
            return redirect('content:showing_object_category', content_type=main_content_type, object=content_type)


        # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        match data:
            case 'word', *args:
                return delete_word(args)

            case 'phrase', *args:
                return delete_phrase(args)

            case 'additionally', pk:
                return delete_additionally(pk)

            case 'group', *args:
                return delete_group(args)

            case 'rule', *args:
                return delete_rule(args)

            case 'article', *args:
                return delete_article(args)

            case 'image', *args:
                return delete_image(args)

            case _:
                print(f'data_delete - {data}')


    def get_right_content(self, *data):

        """ Получаем все необходимое для отображение нужного контента """

        data = list(data)

        match data:
            case 'content_type', content_type:
                context = self.get_context('content_type', content_type)
                template = self.get_template('content_type', content_type)
                return context, template

            case 'show', *args:
                return self.show_something(args)

            case 'add', *args:
                return self.add_something(args)

            case 'update', *args:
                return self.update_something(args)

            case 'delete', *args:
                return self.delete_something(args)

            case _:
                print(f'data1 - {data}')
